package com.kedacom.ctsp.authz;

import com.kedacom.ctsp.authz.aspect.AopAuthorizeAdvisor;
import com.kedacom.ctsp.authz.aspect.AuthorizeService;
import com.kedacom.ctsp.authz.aspect.AuthorizeServiceImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Authentication自动配置类
 *
 * @author xuwei
 * @create 2017-11-28 20:21
 **/
@Configuration
@ConditionalOnProperty(prefix = "commons.authz", value = "enable", matchIfMissing = true)
public class AuthzAutoConfiguration implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof AuthenticationSupplier) {
            AuthenticationHolder.addSupplier(((AuthenticationSupplier) bean));
        }
        return bean;
    }

    @Bean
    @ConditionalOnMissingBean
    public AuthorizeService authorizeService() {
        return new AuthorizeServiceImpl();
    }

    @Bean
    @ConditionalOnMissingBean
    public AopAuthorizeAdvisor aopAuthorizeAdvisor(AuthorizeService authorizeService) {
        return new AopAuthorizeAdvisor(authorizeService);
    }
}
